<?php

require_once 'db.php';

$rating = isset($_POST['rating']) ? $_POST['rating'] : null;

$pageId = isset($_POST['page_id']) ? $_POST['page_id'] : null;
$pageName = isset($_POST['page_name']) ? $_POST['page_name'] : null;
$xhr = isset($_GET['xhr']) ? true : null;  

// Create our query
$query = "
INSERT INTO
	ratings
	(rating, page_id, page_name)
VALUES
	($rating, $pageId, '$pageName')
";
// Run the query on the database and get a response
$result = mysql_query($query);
if(mysql_affected_rows($result) === 1){
	print "Success";
} else {
	print "Failed";
}

// Create our query
$query = "
SELECT
	rating
FROM
	ratings
WHERE
	page_id = '$pageId'
";
// Get the rows that match from the database
$result = mysql_query($query);
// Create an array for our results to be stored in
$ratings = array();
while($row = mysql_fetch_array($result)){
	// For each row, add to the ratings array
	$ratings[] = $row['rating'];
}

if(!empty($ratings)){
	$average = number_format(array_sum($ratings)/count($ratings), 1);
}

?>
